<template>
	<view class="page__content">
		<z-paging ref="paging" v-model="dataList" @query="handleSizeChange" :auto="false" :topZIndex="999"
			:bottomZIndex="10">
			<template #top>
				<!-- <up-navbar :fixed="false" :border="false" :title="titleName" :autoBack="true" :safeAreaInsetTop="true"
					leftIconColor="#fff">
					<template #right>
						<up-icon name="more-dot-fill" color="#fff" class="moremenu"></up-icon>
						<m-bubble type="list" :selectData="formMenus" position="right" topOpsotion="right"
							bgcRgba="#fff" color="#333" @selectFun="TapPopup">
							<up-icon name="more-dot-fill" color="#fff" class="moremenu"></up-icon>
						</m-bubble>
					</template>
				</up-navbar> -->

				<uni-nav-bar leftWidth="140rpx" rightWidth="60rpx" :height="0" :title="titleName" :statusBar="true" :border="false" :fixed="true"
					:showMenuButtonWidth="true">
					<template #left>
						<view class="x-f navbar--left">
							<up-icon name="arrow-left" color="#fff" size="20" @click="goBack"></up-icon>
					
						</view>
					</template>
					<template #right>
						
						<m-bubble 
							type="list" 
							:selectData="formMenus" 
							position="right" 
							boxPosition="none"
							<!-- #ifdef MP-WEIXIN -->
							topOpsotion="left" 
							<!-- #endif -->
							<!-- #ifndef MP-WEIXIN -->
							topOpsotion="right" 
							<!-- #endif -->
							bgcRgba="#fff"
							color="#333"
							 @selectFun="TapPopup">
							<up-icon name="more-dot-fill" :size="20" color="#fff" class="moremenu"></up-icon>
						</m-bubble>
					</template>
				</uni-nav-bar>


				<view class="search x-bc">
					<up-search :placeholder="searchPlaceHolder" v-model="keyword" shape="square"
						:ShowScan="uni.$utils.isPda()" @search="paging.reload()" :inputStyle="{fontSize: '24rpx'}">
						<template #action v-if="!uni.$utils.isPda()">
							<view class="x-c" style="padding: 0 10rpx;">
								<uni-icons type="scan" color="#fff" size="60rpx" @click="searchScanBtn"></uni-icons>
							</view>
						</template>
					</up-search>
				</view>


				<view class="MenuBoxMax">
					<view class="f-dc MenuBox">


						<up-dropdown ref="uDropdownRef">
							<up-dropdown-item
								v-for="row in getNewQueryColumnsByType(queryColumns,(item) => item.colType==3)"
								:rowInfo="row" :title="queryConditions[row.colName + '_show'] || row.colDesc"
								:key="row.colName">
								<template #desc="{element}">
									<view
										style="background-color: #f2f2f2;padding: 6px 15px;color: #999;font-size: 12px;">
										{{element.colDesc}}
									</view>
								</template>
								<m-date-time mode="module" title="DateTitle" :initData="DropDowmMenu_Date[row.colName]"
									@confirm="onDateConfirm($event,row)" @reset="onDateReset(row)">
								</m-date-time>
							</up-dropdown-item>

							<up-dropdown-item
								v-for="row in getNewQueryColumnsByType(queryColumns,(item) => item.colType==2 && item.selDetail.type<3)"
								:key="row.colName" :rowInfo="row" v-model="queryConditions[row.colName]"
								:title="MenuTitleBack(row)" height="40vh"
								:format="{label:'text',icon:'icon',value:'value'}" @change="changeValue($event,row)"
								@reset="onResetByDropdown" :options="getQuerySelectColumns(row)">
								<template #desc="{element}">
									<view
										style="background-color: #f2f2f2;padding: 6px 15px;color: #999;font-size: 12px;">
										{{element.colDesc}}
									</view>
								</template>
							</up-dropdown-item>


							<template #filter class="x-f">
								<view v-if="sortOptions.length" class="x-c"
									style="padding:0 20rpx;border-left:1px solid #cdcdcd;height:100%">
									<uni-icons fontFamily="CustomFontPlatform" style="font-weight: 600;" color="#818181"
										@click="OpenSortPopup"
										:class="sortData.Sort.value.toLowerCase() == 'desc' ? '' : 'icon-flip-vertical'"
										:size="24">{{ uni.$utils.toUniCode('&#xe7e9;')}}</uni-icons>
								</view>

								<view v-if="showMenuFilterFun()" class="x-c"
									style="padding:0 20rpx;color:#818181;height:100%;" @click="openFilterPopup">
									<uni-icons fontFamily="CustomFontPlatform" color="#818181"
										:size="24">{{uni.$utils.toUniCode('&#xe6cb;')}}</uni-icons>
								</view>
							</template>
						</up-dropdown>

					</view>

				</view>

			</template>

			<view class="page__content__main">
				<view class="common__box__child__card" v-for="(item,index) in dataList" :key="index">

					<view class="x-bc common__box__child__card__top">
						<view class="common__box__child__card__top__left">
							<checkbox class="CheckBox" style="margin-right: 6px;" v-if="ShowSelect"
								:checked="item.checked" color="#fff" activeBackgroundColor="#51d0d0"
								activeBorderColor="#51d0d0">
							</checkbox>
							<view>
								<text
									class="common__box__child__card__top__left__title">{{item[titleCol.colName]}}</text>
							</view>
						</view>


						<view class="common__box__child__card__top__right">
							<up-tag class="theTag" :text="item[tag.colName]" v-for="tag in tagCols" :key="tag.colName"
								style="margin-left: 10rpx;" size="medium" plain plainFill
								:type="showTagStatus(item[tag.colName])"></up-tag>
						</view>

					</view>

					<view class="x-bc" @click.stop="ToIndex(item)">

						<view class="formBox" style="flex: 1;">

							<template v-for="col in newColumn" :key="col.colName">
								<view class="common__box__field">
									<view class="common__box__field__label">
										<text>{{col.colDesc}}:</text>
									</view>

									<view class="common__box__field__value">
										<text>{{item[col.colName]}}</text>
									</view>
								</view>
							</template>

						</view>


						<view class="x-ec">
							<view class="priceBox">
							</view>

							<view v-if="listType != 'wait'">
								<up-icon name="arrow-right" color="#cbcbcb" size="16"></up-icon>
							</view>
						</view>

					</view>
				</view>
			</view>


			<template #bottom>
				<view class="page__content__bottom x-bc" :style="uni.$utils.disposeSafeBottomFun()">
					<template>
						<view class="page__content__bottom__left__num-box">
							<text>共计笔数：</text>
							<text class="page__content__bottom__left__num-box__num">{{page.totalCount}}</text>
							<text>笔</text>
						</view>
					</template>

					<view class="x-ec">

						<template v-if="btn_showCondition() && btnAllowShowFun('新增')">
							<button class="content_bottom_primary_Btn CommonBtnSize" @click="insertRow">新增</button>
						</template>
					</view>
				</view>

			</template>

		</z-paging>

		<uni-popup ref="popup_filter" @close="closeSelect" type="right">
			<view class="f-dc" style="width: 80vw;height: 100%;background-color: #fff;"
				:style="uni.$utils.disposeSafeBottomFun()">
				<u-navbar :fixed="false" title="筛选" :autoBack="false" leftIcon=" " :safeAreaInsetTop="true"
					leftIconColor="#fff" style="width: 100%;">
					<view class="u-nav-slot" slot="right">
						<uni-icons color="#fff" type="close" size="30" @click="closeSelect"></uni-icons>
					</view>
				</u-navbar>
				<view class="FilterBox">

					<view class="FiledBox x-bc" style="padding: 15rpx 20rpx;backgroundColor: #fff;"
						v-for="row in getNewQueryColumnsByType(queryColumns,(item) => item.colType==2 && item.selDetail.type==3)"
						:key="row.colName" @click="openBaseScreen(row)">
						<text class="FiledBox_label_x15 FiledBox_grifola" style="color: #333;">{{row.colDesc}}</text>

						<view class="x-ec">
							<text class="FiledBox_value FiledBox_value_x14 FiledBox_grifola"
								style="color: #585858;">{{queryConditions[row.colName+'_show'] || ""}}</text>

							<uni-icons type="right" size="18" color="#999"></uni-icons>
						</view>
					</view>
				</view>

				<view style="padding: 10px;background:#fff;">
					<u-row :gutter="10">
						<u-col span="6">
							<up-button text="重置" @click="resetBtnByFilter"></up-button>
						</u-col>
						<u-col span="6">
							<up-button type="primary" text="确定" @click="submitBtnByFilter"></up-button>
						</u-col>
					</u-row>
				</view>

			</view>
		</uni-popup>

		<!-- 排序弹层 -->
		<uni-popup ref="popup_sort" type="bottom" background-color="#ffffff" @close="closeSortPopup">
			<view class="f-dc" style="max-height: 80vh;">
				<u-navbar :fixed="false" title="排序" :autoBack="false" leftIcon=" " :safeAreaInsetTop="false"
					leftIconColor="#fff" style="width: 100%;">
					<template #right>
						<uni-icons color="#fff" type="close" size="30" @click="closeSortPopup"></uni-icons>
					</template>

				</u-navbar>

				<view style="padding: 15px;flex: 1;overflow: auto;padding-bottom: 20px;">
					<m-sort :sortOptions="sortOptions" :format="sortFormat" :defaultSort="defaultSort"
						:selectSort="sortData.Sort" @change="handleSortChange"></m-sort>
				</view>
			</view>
		</uni-popup>


	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, onUnmounted, computed, reactive, nextTick } from 'vue';
	import { onReady, onLoad, onShow, onUnload } from "@dcloudio/uni-app";
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	let layer = uni.$utils.layer;


	// v-model绑定的这个变量不要在分页请求结束中自己赋值，直接使用即可
	const dataList = ref<any[]>([]);
	const formMenus = [{ // 右侧气泡选项数据
		name: '单据设置',
		value: '',
		icon: 'order',
		show: true,
	},
	{
		name: '刷新',
		value: '',
		icon: 'reload',
		show: true,
	},
	{
		name: '草稿箱',
		value: '',
		icon: 'file-text',
		show: true,
	}]
	// 选中气泡项
	function TapPopup(data : any) {

		switch (data.name) {
			case '单据设置':
				uni.$utils.layer.alert("暂不支持此功能");

				break;
			case '刷新':
				paging.value.reload();
				break;
			case '草稿箱':
				// 跳转到草稿箱列表
				uni.$utils.layer.alert("暂不支持此功能");
				break;
			default:
				break;
		}
	}
	
	// 默认返回页数
	let backNum = ref(1);
	function goBack(str : any = 'back') {
		backNum.value = 1;
		if (str == 'close') {
			let routes = getCurrentPages();
			let routePageCurrent = mainStore.appConfigInfo.routePageCurrent;
			backNum.value = routes.length - routePageCurrent;
		}
	
		uni.navigateBack({
			delta: backNum.value
		})
	}
	
	let value1 = 1;
	let options1 = [{
		label: '默认排序',
		value: 1,
	},
	{
		label: '距离优先',
		value: 2,
	},
	{
		label: '价格优先',
		value: 3,
	}
	]


	// 接收子组件的 confirm 事件（点击确定时触发）
	function onDateConfirm(payload : { start : string; end : string }, row : any) {
		if (uni.$utils.isEmpty(payload.start)) {
			if (row.colName in queryConditions) {
				delete queryConditions[row.colName]
			}

		} else {
			queryConditions[row.colName] = payload.start + '->' + payload.end;
		}
		queryConditions[row.colName + '_show'] = payload.start && payload.end ? String(payload.start + '\n' + payload.end) : "";

		DropDowmMenu_Date[row.colName] = uni.$utils.deepClone(payload);

		uDropdownRef.value.close()
		paging.value.reload();
	}

	// 时间重置按钮
	function onDateReset(row : any) {
		if (queryConditions.hasOwnProperty(row.colName)) {
			if (!uni.$utils.isEmpty(DropDowmMenu_Date)) {
				for (const key in DropDowmMenu_Date) {
					if (DropDowmMenu_Date.hasOwnProperty(key)) {
						if (key == row.colName) {
							DropDowmMenu_Date[key]['SDate'] = '';
							DropDowmMenu_Date[key]['EDate'] = '';
							DropDowmMenu_Date[key]['DateTitle'] = '';
						}
					}
				}
			};
			delete queryConditions[row.colName];
			delete queryConditions[row.colName + '_show'];

		};
		uDropdownRef.value.close()
		paging.value.reload();
	};


	interface filterPopupInstance {
		open : () => void;
		close : () => void;
	};
	let popup_filter = ref<filterPopupInstance | any>(null);
	// 筛选弹层--关闭
	function closeSelect() {
		popup_filter.value.close();
	};
	// 单选下拉
	function openBaseScreen(row : any) {
		let obj = reactive<any>({
			chooseType: row.selDetail.chooseType,
			allowClear: true,
			showSearch: true,
			searchKey: row.selDetail.displayValue,
			serverSearch: true,
			displayValue: row.selDetail.displayValue,
			hiddenValue: row.selDetail.hiddenValue,
			parentValue: row.selDetail.parentValue,
			isPaging: true,
			sql: row.selDetail.dataSource,
			name: row.colDesc,
			colName: row.colName,
			param: {},
			treeObj: {
				treeDataSource: row.selDetail.treeDataSource,
				treeDisplayValue: row.selDetail.treeDisplayValue,
				treeHiddenValue: row.selDetail.treeHiddenValue,
				treeParentValues: row.selDetail.treeParentValues,
			}
		})
		obj.param[row.selDetail.displayValue] = "";
		mainStore.SelectPickerSetting = obj;


		uni.navigateTo({
			url: '/commonPage/Tool/selectPicker' + '?pickerListen=selectPicker_formList'
		})
	};
	// 筛选弹层--重置
	function resetBtnByFilter() {
		// popup_filter.value.close();
		if (!uni.$utils.isEmpty(DropDowmMenu_Date)) {
			for (const key in DropDowmMenu_Date) {
				if (DropDowmMenu_Date.hasOwnProperty(key)) {
					const item = DropDowmMenu_Date[key];
					item['SDate'] = '';
					item['EDate'] = '';
					item['DateTitle'] = '';
				}
			}
		}

		// 遍历对象的所有键，逐个删除
		Object.keys(queryConditions).forEach(key => {
			delete queryConditions[key];
		});
	};
	// 筛选弹层--确认
	function submitBtnByFilter() {
		closeSelect();
		paging.value.reload();
	};
	// 筛选弹层--打开
	function openFilterPopup() {
		popup_filter.value.open();
	};
	// 判断是否存在筛选条件
	function showMenuFilterFun() {
		return queryColumns.value.some(item => item.colType == 2 && item.selDetail?.type == 3);
	};

	// 标题名称
	const titleName = ref<string>("");
	// 模块名称（如：销售订单）
	const moduleName = ref<string>("");
	// 列表类型
	const listType = ref<string>("");
	// 权限字段
	const APPRoleCol = ref<any[]>([]);
	// 已选数据
	const selectedData = ref<any[]>([]);
	// 筛选条件
	let queryConditions = reactive<any>({});
	// 主键字段名
	const ShowKeyName = ref<string>("");
	// 搜索字段
	let keyword = ref<string>("");
	interface pagingInstance {
		reload : () => void;
		refresh : () => void;
		complete : () => void;
		refreshToPage : () => void;
		setLocalPaging : () => void;
	};
	let paging = ref<pagingInstance | any>(null);
	// let pageNo = ref<number>(1);
	let page = reactive({ // 分页数据设置
		pageSize: 30,
		pageIndex: 1,
		totalCount: 0
	})
	// 分页触发事件
	function handleSizeChange(PageNo : number, PageSize : number) {
		uni.$utils.showLoading();

		let _queryColumns = ref([]);
		let _filterCondition = ref(' 1=1 ');
		for (var i = 0; i < queryColumns.value.length; i++) {

			if (queryConditions[queryColumns.value[i].colName] != null && queryConditions[queryColumns.value[i].colName] != undefined) {
				let colName = queryColumns.value[i].colName;
				//日期类型
				if (queryColumns.value[i].colType == 3) {
					let dates = queryConditions[colName].split('->');
					_filterCondition.value += ' and DATEDIFF(day, \'' + dates[0].toString() + '\',' + colName +
						')>=0 and DATEDIFF(day, ' + colName + ', \'' + dates[1].toString() + '\')>=0  ';
				} else if (queryColumns.value[i].colType == 2) {
					_filterCondition.value += ' and ' + colName + '=\'' + queryConditions[colName] + '\' '
				} else if (queryColumns.value[i].colType == 4) {
					_filterCondition.value += ' and ' + colName + '=\'' + queryConditions[colName] + '\' '
				}
			}
		}

		let searchQuerys = queryColumns.value.filter(function (item : any) {
			return item.colType == 1;
		});
		if (searchQuerys.length) {
			let keywordFilter = ref(' 1<>1 ');
			searchQuerys.forEach(function (item : any) {
				keywordFilter.value += ' or ' + item.colName + ' like \'%' + keyword.value + '%\' '
			})
			_filterCondition.value += " and (" + keywordFilter.value + ")";
		}

		if (params.filterCondition) {
			_filterCondition.value += ' and ' + params.filterCondition;
		}
		// pageNo.value = PageNo;
		page.pageIndex = PageNo;


		let searchObj = {
			tableName: params.physicalTableName,
			columnsStr: JSON.stringify(_queryColumns.value),
			currentCol: '',
			pageIndex: PageNo,
			pageSize: +PageSize,
			isForm: (params.isFormList || true).toString(),
			filterCondition: _filterCondition.value,
			defaultOrder: params.defaultOrder || ''
		}

		requestByUrl({
			config: {
				baseURL: "/SQLData/GetDataByPhysicalTableNameByQueryPaging_Uniapp"
			},
			url: '',
			method: 'POST',
			data: searchObj,
			success(ret : any) {

				if (ret.status == 200) {

					if (ret.data.ds.length) {

						if (selectedData.value.length) {
							// 如果有已选中数据，给对应列回显  

							let selectedIDs = selectedData.value.map(item => {
								return item[keyName.value]
							});

							let comparisonSoOrderIDs = new Set(selectedIDs); // 直接使用Set来存储需要匹配的SoOrderID  

							ret.data.ds.forEach((item : any) => {
								item.checked = comparisonSoOrderIDs.has(item[keyName.value]); // 直接使用has的结果来设置checked  
							});

						} else {
							// 如果没有已选中数据，将所有项的checked设置为false  
							// 这里我们直接修改原数组中的对象，而不是创建一个新数组  
							ret.data.ds.forEach((item : any) => {
								item.checked = false;
							});
						};

						uni.$utils.hideLoading(1000);


						if (ret.data.ds1.length > 0) {
							//绑定总长度
							page.totalCount = parseInt(ret.data.ds1[0]["@TotalCount"]);
						}
						// page.pageIndex = page.pageIndex + 1;

						paging.value.completeByTotal(ret.data.ds, page.totalCount);
						// paging.value.completeByTotal(ret.data.ds, page.totalCount);

					} else {

						paging.value.completeByTotal(ret.data.ds, parseInt(ret.data.ds1[0]["@TotalCount"]));
						uni.$utils.hideLoading(1000);
					}

				} else {
					paging.value.complete(false);
					uni.$utils.hideLoading(1000);
				}
			}
		})
	};
	function searchScanBtn() { // 搜索栏扫码

		uni.$utils.$scanPopup.openScan({
			onlyFromCamera: false,
			scanType: ['qrCode', 'barCode'],
			success: (res : any) => {

				uni.showToast({
					title: res.result
				})
			}
		});
	}

	function initConfig(objName : string) {
		requestByUrl({
			config: {
				baseURL: "/AppFormList/GetDataByName"
			},
			url: '',
			method: 'POST',
			data: { objName: objName },
			success(ret : any) {
				if (ret.status == 200 && ret.data.ds.length) {


					selectedData.value = [];
					for (const key in queryConditions) delete queryConditions[key];

					const filterCondition = ret.data.ds[0]["filterCondition"] || "";

					const columnsConfig = JSON.parse(ret.data.ds[0]["columnsConfig"] || "[]");
					const filterKeyData = columnsConfig.filter((item : any) => item.isKey);

					if (filterKeyData.length) {
						ShowKeyName.value = filterKeyData[0]['colName'];
					}

					const worksConfigData = JSON.parse(ret.data.ds[0]["worksConfig"] || "[]");
					const filteredArray = worksConfigData.filter((item : any) =>
						evaluateShowCondition(item.show)
					);

					tableConfig({
						columns: columnsConfig,
						workList: filteredArray,
						crudList: JSON.parse(ret.data.ds[0]["crudConfig"] || "[]"),
						params: {
							isFormList: ret.data.ds[0]["isFormList"],
							physicalTableName: ret.data.ds[0]["physicalTableName"],
							isPaging: ret.data.ds[0]["isPaging"],
							filterCondition,
							defaultOrder: ret.data.ds[0]["defaultOrder"],
							detailName: ret.data.ds[0]["detailName"],
							isFormEdit: false,
							rowClassCol: ret.data.ds[0]["rowClassCol"],
							onReadyCallBack: ret.data.ds[0]["onReadyCallBack"],
							colClassCol: ret.data.ds[0]["colClassCol"],
						}
					});
				}
			}
		});
	}

	// ⚠️ 使用 eval 不安全，这里假设仅内部使用配置时评估条件表达式
	function evaluateShowCondition(conditionStr : string) {
		try {
			return eval(conditionStr);
		} catch (e) {
			return false;
		}
	}

	const columns = ref<any[]>([]);
	const workList = ref<any[]>([]);
	const crudList = ref<any[]>([]);
	const params = reactive<any>({});
	let titleCol = ref<any>({});
	const tagCols = ref<any[]>([]);
	const keyName = ref<string>("");
	const keyValue = ref<string>("");
	let queryColumns = ref<any[]>([]);
	let DropDowmMenu_Date = reactive<any>({});
	let searchPlaceHolder = ref<string>("");
	let sortOptions = ref<any[]>([]);
	// 选中的排序数据
	let sortData = reactive<any>({
		OrderBy: '',
		Sort: {
			value: ''
		}
	});
	// 默认选中的排序id
	let defaultSort = ref<any>(null);
	// 升降序数据
	let sortFields = [{
		text: '升序',
		value: 'ASC'
	}, {
		text: '降序',
		value: 'DESC'
	}];
	// 排序字段定义
	let sortFormat = {
		id: 'id',
		name: 'colDesc',
		text: 'text',
		value: 'value',
	};

	interface sortPopupInstance {
		open : () => void;
		close : () => void;
	};
	let popup_sort = ref<sortPopupInstance | any>(null);
	// 点击排序
	function OpenSortPopup() {
		popup_sort.value.open()
	};
	// 关闭排序弹层
	function closeSortPopup() {
		popup_sort.value.close();
	};
	// 选中排序字段
	function handleSortChange(sortDataInfo : any) {

		const {
			sort: {
				colName,
				id
			},
			item
		} = sortDataInfo;
		params.defaultOrder = `${colName} ${item.value}`;
		closeSortPopup();
		paging.value.reload();


		setTimeout(() => {
			sortData.OrderBy = colName;
			defaultSort.value = id;
			sortData.Sort = item;
		}, 500);
	}

	function tableConfig(options : any) {
		const aDataMap = new Map();
		if (Array.isArray(APPRoleCol.value)) {
			for (const row of APPRoleCol.value) {
				if (row?.ColName !== undefined) {
					aDataMap.set(row.ColName, row);
				}
			}
		}

		if (Array.isArray(options?.columns)) {
			for (const item of options.columns) {
				const colName = item?.colName;
				if (colName) {
					const typeInfo = aDataMap.get(colName);
					if (typeInfo) {
						const { IsViewRole, IsEditRole } = typeInfo;
						item.isHidden = !IsViewRole;
						item.isReadOnly = !IsViewRole && !IsEditRole;
					}
				}
			}
		}


		columns.value = options.columns;
		workList.value = options.workList;
		crudList.value = options.crudList;
		Object.assign(params, options.params);

		const titleCols = columns.value.filter(item => item.isTitle === true);
		if (titleCols.length > 0) {
			titleCol.value = titleCols[0];
		}

		tagCols.value = columns.value.filter((item : any) => item.isFold === true);

		const keyColumn = columns.value.filter((item : any) => item.isKey === true);
		if (keyColumn.length > 0) {
			keyName.value = keyColumn[0].colName;
		}

		initSelectValue();
		queryColumns.value = columns.value.filter(function (item) {
			// return item.isColQuery == true && item.isTitle == false
			return item.isColQuery == true
		});
		let backDate = ref<any[]>([]);
		backDate.value = queryColumns.value.filter(row => row.colType == 3);
		let customValue = reactive<any>({
			DateTitle: '',
			SDate: '',
			EDate: '',
		})
		let newObject = backDate.value.reduce((acc, curr) => {
			// 将当前对象的 colName 作为新对象的属性名  
			// 将自定义的对象作为属性值  
			acc[curr.colName] = customValue;
			return acc;
		}, {});
		// DropDowmMenu_Date = uni.$utils.deepClone(newObject);
		Object.assign(DropDowmMenu_Date, newObject)

		//文字搜索框内容
		searchPlaceHolder.value = queryColumns.value.filter(function (item : any) {
			return item.colType == 1;
		}).map(function (item : any) {
			return item.colDesc;
		}).join('/');
		// 过滤出属于排序的数据
		sortOptions.value = queryColumns.value.filter(item => item.isOrder)
			.map((item, index) => {
				return {
					...item,
					id: index,
				}
			});

		let SortType = ref<any>(params.defaultOrder.split(' '));

		if (SortType.value.length == 1) {
			SortType.value.push('desc')
		}

		// 找到对应的排数数据
		let defaultData = sortOptions.value.filter((item : any) => {
			return item.colName == SortType.value[0]
		})
		if (defaultData.length) {
			sortData.OrderBy = SortType.value[0];
			defaultSort = defaultData[0]['id'];
			sortData.Sort = sortFields.filter(item => (item.value).toUpperCase() == (SortType.value[1])
				.toUpperCase())[0];
		}
		setTimeout(() => {
			paging.value.reload();
		}, 500);
	}

	/**
	 * 过滤下拉菜单数组数据
	 * @param {Array} 过滤数组
	 * @param {Function} 过滤条件
	 * @return {Array} 返回过滤后的数据
	 */
	function getNewQueryColumnsByType<T>(array : T[], condition : (item : T) => boolean) : T[] {
		// 创建结果数组
		const result : T[] = [];

		// 遍历数组，检查每个元素是否满足条件
		for (const item of array) {
			if (condition(item)) {
				result.push(item);
			}
		}

		return result;
	}

	function initSelectValue() {
		interface RequestItem {
			index : number;
			request : any; // 应为 Promise 类型，具体看你的实现
		}

		let requestSelectSql = ref<RequestItem[]>([]);

		for (let i = 0; i < columns.value.length; i++) {
			let col = reactive(columns.value[i]);
			if (col.colType == 2 && col.selDetail?.type == 1) {

				const sql = col.selDetail.dataSource;
				col.selDetail.sqlDataSource = [];
				col.selDetail.originDataSource = [];

				let requestSql = PromiseRequestByUrl({
					config: {
						baseURL: "/SQLData/GetDataBySql"
					},
					url: '',
					method: 'POST',
					data: { sql }
				});

				requestSelectSql.value.push({
					index: i,
					request: requestSql
				});
			}
		};
		requestSelectSql.value.forEach(item => {
			item.request.then((data : any) => {
				const ds = data.data.ds;
				columns.value[item.index].selDetail.sqlDataSource = ds;
				columns.value[item.index].selDetail.originDataSource = ds;
			});
		});
	}


	// 转换后的computed属性
	const newColumn = computed(() => {
		return columns.value.filter(col => {
			return !col.isHidden && !col.isTitle && !col.isFold && isShowColumns(col);
		});
	});

	function isShowColumns(colObj : any) {
		let showColumns = uni.getStorageSync(moduleName.value + '_ShowColumns');
		let isShow = true;
		if (showColumns) {
			let flag = showColumns.some((item : any) => item == colObj.colName)
			if (!flag) {
				isShow = false;
			}
		}
		return isShow;
	}


	// 是否开启多选
	let ShowSelect = ref(false);

	//显示标签颜色状态
	function showTagStatus(tagName : string) {
		if (tagName.indexOf('通过') >= 0 || tagName.indexOf('成功') >= 0) {
			return "success";
		} else {
			return "warning";
		}
	}


	let stickShow = ref(false);

	interface DropdownInstance {
		open : () => void;
		close : () => void;
		toggle : () => void;
		// 可以根据实际需要添加更多方法
	}
	let uDropdownRef = ref<DropdownInstance | any>(null);
	// 下拉框打开时触发
	function mDropdownOpen() {
		stickShow.value = false;
	};

	function MenuTitleBack(row : any) {
		let FilterData = getQuerySelectColumns(row).filter((item : any) => {
			return item.value == queryConditions[row.colName];
		});
		if (FilterData.length) {

			return FilterData[0]['text'];
		} else {

			return row.colDesc || '请选择'
		}
	};
	//获取查询下拉数据源
	function getQuerySelectColumns(row : any) {

		let MapData = row.selDetail?.sqlDataSource.map(function (item : any) {
			return {
				text: item[row.selDetail.displayValue],
				value: item[row.selDetail.hiddenValue]
			}
		});
		return MapData
	}
	// 切换普通下拉cell选项
	function changeValue(event : any, row : any) {
		queryConditions[row.colName] = event.value;
		queryConditions[row.colName + '_show'] = event.text;
		paging.value.reload();
	}
	function onResetByDropdown(data : any) {

		if (queryConditions.hasOwnProperty(data.colName)) {
			delete queryConditions[data.colName];
		}
		uDropdownRef.value.close();
		paging.value.reload();
	}


	function ToIndex(obj : any) {
		if (ShowSelect.value) {
			toggleSelection(obj)
			return
		}
		if (listType.value == 'wait') { // 待办
			return
		};
		if (listType.value == 'audit') {
			let returnData = {
				detailTitle: titleName.value,
				detailName: obj['B_KeyDetail'],
				keyName: obj['B_KeyCol'],
				keyValue: obj['BillID'],
				dataInfo: {
					titleColName: '',
					showColumnsInfo: [],
					tagColumnsInfo: [],
				}
			}
			inventoryStore.MenuDetail = returnData;
			uni.navigateTo({
				url: '/commonPage/Form/Edit',
				success() {

				}
			})
		} else {
			// 查看详情
			//查看详情
			let returnData = reactive<any>({
				detailTitle: titleName.value,
				detailName: params.detailName,
				keyName: keyName.value,
				keyValue: obj[keyName.value],
				dataInfo: {
					titleColName: obj[titleCol.value.colName],
				}
			});

			let showColumnsInfo = columns.value.filter(function (col : any) {
				return !col.isHidden && !col.isTitle && !col.isFold && isShowColumns(col);
			}).map(function (col) {
				return {
					name: col.colDesc,
					value: obj[col.colName]
				}
			});

			let tagColumnsInfo = []
			tagColumnsInfo = tagCols.value.map(function (tag : any) {
				return {
					text: obj[tag.colName],
					type: showTagStatus(obj[tag.colName])
				}
			});
			returnData.dataInfo["showColumnsInfo"] = showColumnsInfo;
			returnData.dataInfo["tagColumnsInfo"] = tagColumnsInfo;
			inventoryStore.MenuDetail = returnData;

			uni.navigateTo({
				url: '/commonPage/Form/index'
			})
		};
	};

	function toggleSelection(data : any) {

	}

	//按钮显示条件判断
	function btn_showCondition() {
		try {
			let result = true;
			let showScript = crudList.value[0].show;

			if (showScript) {
				eval("result=(" + showScript + ")");
			}
			return result;
		} catch (e) {
			return false;
		}
	};
	// 判断当前按钮是否允许显示
	function btnAllowShowFun(str : string) {
		const filterUnPermissionConfig = permissionStore.filterUnPermissionConfig;
		// 检查是否存在任何项的 FunName 与传入的字符串相匹配
		const isFunctionDenied = filterUnPermissionConfig.some((item : any) => item.FunName === str);
		return !isFunctionDenied;
	};

	const CommonBtnSize = reactive({
		"min-width": "160rpx",
		"font-size": "14px",
		"padding": "2px 4px"
	})
	// 点击新增
	function insertRow() {
		//查看详情
		let returnData = {
			detailTitle: titleName.value,
			detailName: params.detailName,
			keyName: keyName.value,
			keyValue: 0,
			dataInfo: {
				//titleColName: obj[that.titleCol.colName],
			}
		};
		inventoryStore.MenuDetail = returnData;
		uni.navigateTo({
			url: '/commonPage/Form/Edit'
		});
	};

	function refreshToPageFun(dataId : any) {
		setTimeout(() => {
			paging.value.refreshToPage(page.pageIndex).then((ret : any) => {

				//状态标签
				let tagCols = columns.value.filter(function (item) {
					return item.isFold == true
				});
				let filterData = ret.totalList.filter((item : any) => {
					return item[keyName.value] == dataId
				})
				if (filterData.length) {



					let tagColumnsInfo = []
					tagColumnsInfo = tagCols.map(function (tag) {
						return {
							text: filterData[0][tag.colName],
							type: showTagStatus(filterData[0][tag.colName])
						}
					});


					// 找到对应的数据，回写给index页面
					uni.$emit('newListData', {
						data: tagColumnsInfo
					})
				}

			});
		}, 1000);
	}

	onLoad(async (option : any) => {
		if (uni.$utils.isEmpty(option)) {
			listType.value = "list";
		} else {
			listType.value = option.type;
		}

		const menuObj = reactive<{
			APFunName : string,
			[key : string] : any
		}>(inventoryStore.Menu);
		permissionStore.getUnPermissionConfigInfo(menuObj.APFunName);

		await permissionStore.getAPPRoleColFunByRoleID({
			request: request,
			moduleName: menuObj.APFunName,
			moduleType: 'formlist'
		}).then((ret : any) => {
			if (ret.status === 200) {
				APPRoleCol.value = ret.data.ds;
			}
		});

		titleName.value = menuObj.APFunName + '列表';
		moduleName.value = menuObj.Para;
		initConfig(moduleName.value);
	});

	onReady(() => {
		uni.$on("selectPicker_formList", ((ret : any) => {

			//单选下直接赋值
			let curCol = columns.value.filter(function (item) {
				return item.colName == ret.colName
			});
			queryConditions[ret.colName] = ret.data[curCol[0].selDetail.hiddenValue];
			queryConditions[ret.colName + '_show'] = ret.data[curCol[0].selDetail.displayValue];
		}));

		// 监听刷新
		uni.$on('FormInitToRefresh', (data) => {
			refreshToPageFun(data.keyID);
		})
	});
	onUnload(() => {
		uni.$off("selectPicker_formList");
		uni.$off("FormInitToRefresh");

	})
</script>


<style lang="scss">
	.page__content {
		height: 100vh;
		background-color: #f2f2f2;

		.icon-flip-vertical {
			display: inline-block;
			/* 或者其他适合你的布局的display值 */
			transform: scaleY(-1);
			/* 垂直翻转 */
		}

		uni-button {
			margin-left: initial !important;
			margin-right: initial !important;
		}


		.common__box__child__card {
			margin: 5rpx 15rpx 15rpx;

			&__top {
				padding: 10rpx 0;
				border-bottom: 1px solid #e5e5e5;
			}

		}

		.common__box__field {
			color: #999999;
		}




		.MainPopup {
			flex: initial !important;

			.PopupContent {
				display: flex;
				flex-direction: column;
				min-height: 240px;
				width: 90vw;
			}

			.u-transition {
				z-index: 99999 !important;
			}


			.PopupMainBox {
				padding: 12px 10px 6px;
				flex: 1;
				// overflow: auto;

				.CellBox {
					margin-bottom: 20px;

					.LeftBox {
						font-size: 14px;
						color: #999;
						margin-right: 10px;
					}
				}

				.uni-input-placeholder {
					color: #6a6a6a !important;
					font-size: 12px !important;
				}
			}

			.PopupBottomBox {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding: 10px 10px;

				.CancelBtn {
					background-color: #fff;
					color: #51d0d0;
					border: 1px solid #51d0d0;
					min-width: 80px;
				}

				.ComfirmBtn {
					background-color: #51d0d0;
					color: #fff;
					min-width: 80px;
					margin-left: 10px !important;
				}
			}
		}

		.MenuBoxMax {
			position: relative;
			background-color: #fff;
			width: 100%;
			border-bottom: 4px solid #f2f2f2;

			// .MenuBox {
			// 	position: absolute;
			// 	top: 0;
			// 	left: 0;
			// 	width: 100%;
			// 	background-color: #fff;

			// 	.selectSearchDom {
			// 		padding-right: 10rpx;
			// 	}
			// }
		}

		.MainBox {
			// flex: 1;
			// overflow: auto;
			padding: 10rpx;

			// 表单1
			.u-form {
				// padding: 0px 10px;

				.u-form-item {
					background-color: #fff;
					padding: 0 16px;
				}


				.TopOption {

					.u-form-item__body {
						flex-direction: column !important;
					}
				}

				// 起止时间
				.ChoiceTimesBox {
					width: 100%;
					display: flex;
					align-items: center;
					// background-color: #fff;
					// padding: 18px 10px;
					// margin-top: 10px;

					.TimeBox {
						flex: 1;
						display: flex;
						align-items: center;
						justify-content: space-evenly;

						.timer {
							width: 100%;
							flex: 2;
							display: flex;
							flex-direction: column;
							// align-items: center;
							font-size: 16px;
							color: #333;

							text:first-child {
								margin-bottom: 10px;
								font-weight: 600;
							}

							text:last-child {
								height: 20px;
							}
						}

						.Icon {
							flex: 1;
						}
					}
				}


				// 上传-删除图标
				.u-upload__deletable {
					width: 20px;
					height: 20px;

					.u-upload__deletable__icon {
						right: -1px !important;

						.u-icon__icon {
							font-size: 20px !important;
							line-height: 16px !important;
						}
					}
				}
			}
		}

		.BottomBox {
			width: 100%;
			// height: 70px;
			// line-height: 70px;
			padding: 6px 15px;
			border-top: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: #fff;
			// padding-bottom: constant(safe-area-inset-bottom) !important;
			// padding-bottom: env(safe-area-inset-bottom) !important;
		}

		.moremenu {
			margin-right: 10rpx;
			margin-top: 15rpx;
		}

		.search {
			background-color: #fff;
			background-color: #51d0d0;
			padding: 6px 2px 6px 6px;
			// padding: 6px 10px;

			.scanQrCode {
				width: 20rpx;
				padding: 5rpx;
			}
		}

		.list {
			background-color: #999;
		}

		.bottomTool {
			background: #fff;
			padding: 15rpx;
			border-top: 2px solid #f2f2f2;
		}

		.operTotal {
			font-size: 14px;
			color: #333;
		}

		.operBtn {
			width: fit-content;
		}

		.FilterBox {
			background-color: #e8e8e8;
			flex: 1;

			.FiledBox {
				position: relative;

				&::after {
					position: absolute;
					box-sizing: border-box;
					content: ' ';
					pointer-events: none;
					right: 16px;
					bottom: 0;
					left: 16px;
					border-bottom: 1px solid #ebedf0;
					-webkit-transform: scaleY(0.5);
					transform: scaleY(0.5);
				}

				&:last-child::after {
					border-bottom: none;
				}
			}
		}
	}
</style>